//课程分类
function course_type(){
    var companyId = $("#companyId").val();
    var courseTreeId = "course_treeId";

    var _this = this;

    var course_type_options = {
        zNodes: '',
        rMenu: ''
    };

    var rMenu = $("#rMenu");

    _this.setting = {
        view: {
            dblClickExpand: false,
            fontCss: getFontCss
        },
        callback: {
            onRightClick: function(event, treeId, treeNode){
                var id = treeNode.id.toString();
                if(id.indexOf("yourself_") != -1){
                    return;
                }
                _this.onRightClick(event, treeId, treeNode);
            },
            onClick: function(e,treeId, treeNode){
                _this.onClick(e,treeId, treeNode);
            }
        }
    };

    //点击
    _this.onClick = function(e,treeId, treeNode) {
        zTree = $.fn.zTree.getZTreeObj(courseTreeId);
        zTree.selectNode(treeNode);
        $("#intTypeId").val(treeNode.id);
        if($("#courseManager").val()=='courseManager'){
            course_list.search();
        }else if( $("#courseManager").val() == "courseSelfManager"){
            course_self_list.search();
        }
        else {
            private_selectCourse.search();
        }
    };

    _this.onRightClick = function(event,treeId, treeNode) {
        var scrollTop = $(window).scrollTop();
        var pageX = event.clientX;
        var pageY = event.clientY + scrollTop;
        zTree = $.fn.zTree.getZTreeObj(courseTreeId);
        zTree.selectNode(treeNode);
        var value = $('#click_course_status span[class="active"]').attr("data-value");
        if("1" == value){
           showRMenu(pageX ,pageY , treeNode);
        }
    }


    //初始化树
    _this.iniTree = function(url){
        var chrSource = $("#chrSource").val() == undefined ?"" : $("#chrSource").val();
        url += '?chrSource='+ chrSource +'&companyId=' + companyId;
        var result = _this.ajax(url);
        course_type_options.zNodes = eval(result);
        $.fn.zTree.init($("#course_treeId"), _this.setting, course_type_options.zNodes);
        //默认选中根节点
        var treeObj = $.fn.zTree.getZTreeObj(courseTreeId);
        var rootNodes = treeObj.getNodesByFilter(function(node){return node.level==0;});
        var rootNode = rootNodes[0];
        // 默认选中根节点
        treeObj.selectNode(rootNode);
    };


    /* //树搜索
     _this.tree_search = function(){
         $("#search_key").bind("propertychange", _this.searchNode).bind("input", _this.searchNode);
     };

     _this.searchNode = function(e) {
         var zTree = $.fn.zTree.getZTreeObj("course_treeId");
         var value = $.trim($("#search_key").val());
         var	nodeList = zTree.getNodesByParamFuzzy("name", value);
         if(value){
             _this.highlightNodes(nodeList, true);
         }else{
             _this.highlightNodes(nodeList, false);
         }
     };

     _this.highlightNodes = function(nodeList, highlight) {
         var zTree = $.fn.zTree.getZTreeObj("course_treeId");
         var len = nodeList.length;
         for( var i=0; i<len; i++) {
             nodeList[i].highlight = highlight;
             zTree.updateNode(nodeList[i]);
         }
     };*/

    _this.ajax = function(url, param, type){
        var result;
        $.ajax({
            url: url,
            async: false,
            type: 'post',
            data: param,
            success: function(data){
                result = data.result;
            }
        });
        return result;
    };

    //添加节点(1:平级节点；2：子级节点)
    _this.addTreeNode = function(ntp){
        hideRMenu();
        var selectedNodes = $.fn.zTree.getZTreeObj(courseTreeId).getSelectedNodes();
        if("1" == ntp && "自制课程" == selectedNodes[0].name){
            layer.msg("根节点不能新增平级节点");
            return;
        }
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        // 请输入节点名称
        var promptIndex = layer.prompt({
            title : '输入要添加的节点名称，并确认',
            formType : 2,
            maxlength:40
        }, function(text) {
            var params = {
                'nodeId': selectedNode.id,
                'nodeName': $.trim(text),
                'nodeType': ntp
            };
            if(text.length>40){
                layer.msg("课程类别超出长度限制");
                return;
            }
            if(isExistName($.trim(text))){
                layer.msg("课程类别已存在");
                return;
            }
            $.ajax({
                url: appPath + '/admin/exCourseTypeSelf/saveNode',
                async: false,
                type: 'post',
                data: params,
                success: function(data){
                    var result = data['result'];
                    if(result){
                        layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                            layer.close(index);
                            layer.close(promptIndex);
                            var url = appPath + '/admin/exCourseTypeSelf/getTree';
                            _this.iniTree(url);
                        });
                    }else{
                        layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                    }
                }
            });
        });
    }

    //修改名称
    _this.renameTreeNode = function(e){
        hideRMenu();
        var selectedNodes = $.fn.zTree.getZTreeObj(courseTreeId).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var node='';
        if (selectedNodes.length > 0) {
            node = selectedNodes[0].getParentNode();
        }
        // 请输入节点名称
        var promptIndex = layer.prompt({
            title : '输入新的节点名称，并确认',
            formType : 2,
            maxlength:40,
            value: selectedNode.name
        }, function(text) {
            layer.close(promptIndex);
            var selectedNode = selectedNodes[0];
            var params = {
                'companyId': companyId,
                'nodeId': selectedNode.id,
                'nodeName': $.trim(text)
            };
            if(isExistName($.trim(text))){
                layer.msg("课程类别已存在");
                return;
            }
            $.ajax({
                url: appPath + '/admin/exCourseTypeSelf/updateNode',
                async: false,
                type: 'post',
                data: params,
                success: function(data){
                    var result = data['result'];
                    if(result){
                        layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                            layer.close(index);
                            // 刷新树
                            var url = appPath + '/admin/exCourseTypeSelf/getTree';
                            course_type.iniTree(url);
                        });
                    }else{
                        layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                    }
                }
            });
        });
    };

    //删除节点
    _this.removeTreeNode = function(e){
        hideRMenu();
        var selectedNodes = $.fn.zTree.getZTreeObj(courseTreeId).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var params = {
            'intId': selectedNode.id
        };
        if (selectedNode.children && selectedNode.children.length > 0) {
            layer.alert('操作失敗，您要删除的节点包含子节点', {icon: 2,  skin: 'layer-ext-moon'});
        }else{
            layer.confirm('确定删除该节点吗？', {
                btn: ['删除','取消'] //按钮
            }, function(){
                _this.remove(params);
            });
        }
    };

    // 上移
    _this.moveUp = function(){
        var selectedNodes = $.fn.zTree.getZTreeObj(courseTreeId).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var params = {
            "type":"1",
            'nodeId': selectedNode.id
        };
        $.ajax({
            url: appPath + '/admin/exCourseTypeSelf/moveNode',
            async: false,
            type: 'post',
            data: params,
            success: function(data){
                var result = data['result'];
                var message;
                if(result){
                    layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                        layer.close(index);
                        // 刷新树
                        var url = appPath + '/admin/exCourseTypeSelf/getTree';
                        course_type.iniTree(url);
                    });
                }else{
                    layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                }
            }
        });
    };

    // 下移
    _this.moveDown = function(){
        var selectedNodes = $.fn.zTree.getZTreeObj(courseTreeId).getSelectedNodes();
        if(selectedNodes.length==0){
            layer.alert('请选择节点', {icon: 2,  skin: 'layer-ext-moon'});
            return;
        }
        var selectedNode = selectedNodes[0];
        var params = {
            "type":"2",
            'nodeId': selectedNode.id
        };
        $.ajax({
            url: appPath + '/admin/exCourseTypeSelf/moveNode',
            async: false,
            type: 'post',
            data: params,
            success: function(data){
                var result = data['result'];
                var message;
                if(result){
                    layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                        layer.close(index);
                        // 刷新树
                        var url = appPath + '/admin/exCourseTypeSelf/getTree';
                        course_type.iniTree(url);
                    });
                }else{
                    layer.alert((data['message'])?data['message']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                }
            }
        });
    };

    // 删除节点
    _this.remove = function(params){
        $.ajax({
            url: appPath + '/admin/exCourseTypeSelf/deleteNode',
            async: false,
            type: 'post',
            data: params,
            success: function(data){
                var result = data['result'];
                if(result == "success"){
                    layer.alert('操作成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                        layer.close(index);
                        // 刷新树
                        var url = appPath + '/admin/exCourseTypeSelf/getTree';
                        course_type.iniTree(url);
                    });
                }else{
                    layer.alert((data['errorMsg'])?data['errorMsg']:'操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
                }
            }
        });
    };

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function showRMenu(x, y,treeNode) {
        if("0"==treeNode.level){//根节点
            $("#m_add").show();
            $("#m_p_add").hide();
            $("#m_del").hide();
            $("#m_reset").hide();
            $("#m_moveup").hide();
            $("#m_movedown").hide();
        }else{
            $("#m_add").show();
            $("#m_p_add").show();
            $("#m_del").show();
            $("#m_reset").show();
            $("#m_moveup").show();
            $("#m_movedown").show();
        }
        $("#rMenu").css({"top":y+"px", "left":x+"px", "visibility":"visible"});

        $("body").bind("mousedown", onBodyMouseDown);
    }


    function onBodyMouseDown(event){
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
            rMenu.css({"visibility" : "hidden"});
        }
    }

    function isExistName(nodeName) {
        var flag = false;
        $.ajax({
            url: appPath + "/admin/exCourseTypeSelf/isExistName",
            data: {"nodeName": nodeName,"companyId": companyId},
            dataType: "json",
            async:false,
            type: "post",
            success: function (data) {
                var result = eval(data).isExistName;
                if (result == "true") {
                    flag = true;
                }
            }
        });
        return flag;
    }
};

var course_type = new course_type();

//搜索高亮
function getFontCss(treeId, treeNode){
    return (!!treeNode.highlight)?{'color': "#A60000", 'font-weight':"bold"}:{'color': "#333", 'font-weight':"normal"};
}
